<?php
namespace common\models\userFund;

use common\models\Common;
use common\models\im\Im;
use common\models\pay\Alipay;
use common\models\Status;
use common\models\user\User;
use common\models\userReceipt\ReceiptBank;
use yii\base\Exception;
use Yii;
/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserWithdrawOrder extends Common
{
    public static function tableName()
    {
        return '{{%user_withdraw}}';
    }
    
    //获取用户
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    //获取银行卡
    public function getBank() {
        return $this->hasOne(ReceiptBank::className(), ['id' => 'bank_id']);
    }

    /**
     * 生成订单号
     * @return string
     */
    public function _createOrderNumber() {
        do {
            $order = "W" . date("ymdH") . rand(100, 999);

            $count = static::getCountByWhere(['order_number' => $order]);

        } while($count > 0);

        return $order;
    }


    // 拒绝提现
    public function cancelOrder($orderNumber = 0, $reason = '') {
        $info = static::getOneByWhere(['order_number' => $orderNumber]);

        if ($info['status'] != Status::WITHDRAW_STATUS_DOING) {
            throw new Exception("该订单已处理");
        }

        $up['status'] = Status::WITHDRAW_STATUS_FAILED;
        $up['deal_time'] = date("Y-m-d H:i:s");
        $up['failed_reason'] = $reason;
        $res = static::updateData($up, ['order_number' => $orderNumber]);
        if ($res < 1) {
            throw new Exception('该订单正在处理中');
        }
        # 返还金额
        $totalMoney  = $info['money'];
        $type = $info['type'];
        if ($type == Status::WITHDRAW_TYPE_MONEY) {
            // 余额信息
            UserMoneyLog::record(
                $info['user_id'],
                Status::PROP_TYPE_MONEY,
                Status::MONEY_LOG_TYPE_WITHDRAW_DEFEAT,
                floatval(1 * $totalMoney),
                Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_WITHDRAW_DEFEAT] ?? '',
                '提现撤回，单号：【'.$info['order_number'].'】',
                $info['id']
            );
        }

        if ($type == Status::WITHDRAW_TYPE_SHOP) {
            // 橱窗余额
            UserMoneyLog::record(
                $info['user_id'],
                Status::PROP_TYPE_SHOP_MONEY,
                Status::SHOP_MONEY_LOG_TYPE_WITHDRAW_DEFEAT,
                floatval(1 * $totalMoney),
                Status::SHOP_MONEY_LOG_TYPE_MAP[Status::SHOP_MONEY_LOG_TYPE_WITHDRAW_DEFEAT] ?? '',
                '提现撤回，单号：【' . $info['order_number'].'】',
                $info['id']
            );
        }

        $moneyTypeName = Status::WITHDRAW_TYPE_MAP[$type] ?? '';

        // 发送IM信息
        $userMessage = [];
        $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
        $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
        $userMessage['title'] = $moneyTypeName."提现撤回";
        $userMessage['money_title'] = "撤回金额";
        $userMessage['money'] = (string) abs($totalMoney);
        $userMessage['desc'] = "提现撤回".floatval($totalMoney)."元";
        $userMessage['mark'] = $reason ? $reason : "你可以在钱包中查看相关记录";
        $userMessage['time'] = date('Y-m-d H:i:s');
        $config = static::getCommonByKey('money_user_id');
        $userInfo = User::getOneByWhere(['id' => $info['user_id']]);
        (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);

    }

    // 通过提现
    public function successOrder($orderNumber = '') {
        $info = static::getOneByWhere(['order_number' => $orderNumber]);

        if ($info['status'] == Status::WITHDRAW_STATUS_DONE) {
            throw new Exception("该订单已处理");
        }


        $up['status'] = Status::WITHDRAW_STATUS_DONE;
        $res = static::updateData($up, ["order_number" => $orderNumber]);
        if (empty($res)) {
            throw new Exception('该订单正在处理中');
        }

        $up['deal_time'] = date("Y-m-d H:i:s");
        $res = static::updateData($up, ['order_number' => $orderNumber]);
        if ($res == false) {
            throw new Exception('提现失败');
        }
    }

    //  查询提现状态
    public function queryWithdraw() {

        $list = static::getByWhere(['status' => Status::WITHDRAW_STATUS_QUERYING]);

        foreach ($list as $key => $value) {
            $trans = Yii::$app->getDb()->beginTransaction();

            try {

                $alipayResult = (new Alipay())->queryFundTransUniTransfer($value['order_number']);
                if ($alipayResult->status != "SUCCESS") {
                    continue;
                }
                if ($value['status'] == Status::WITHDRAW_STATUS_DONE) {
                    throw new Exception("该订单已处理");
                }


                $up['status'] = Status::WITHDRAW_STATUS_DONE;
                $res = static::updateData($up, ["id" => $value['id']]);
                if (empty($res)) {
                    throw new Exception('该订单正在处理中');
                }

                $up['deal_time'] = date("Y-m-d H:i:s");
                $res = static::updateData($up, ["id" => $value['id']]);
                if ($res == false) {
                    throw new Exception('提现失败');
                }

                $trans->commit();
            } catch (Exception $e) {
                $trans->rollBack();

            }
        }


    }

}
